extends Control
class_name BattleScene

## 回合制战斗场景
## 实现自动攻击的回合制战斗系统

signal battle_ended(victory: bool, final_player_hp: int, defeated_enemy_data: Dictionary)

@onready var player_sprite: TextureRect = $PlayerSide/PlayerSprite
@onready var enemy_sprite: TextureRect = $EnemySide/EnemySprite
@onready var player_hp_bar: ProgressBar = $PlayerSide/PlayerInfo/HPBar
@onready var enemy_hp_bar: ProgressBar = $EnemySide/EnemyInfo/HPBar
@onready var player_name_label: Label = $PlayerSide/PlayerInfo/NameLabel
@onready var enemy_name_label: Label = $EnemySide/EnemyInfo/NameLabel
@onready var player_hp_label: Label = $PlayerSide/PlayerInfo/HPLabel
@onready var enemy_hp_label: Label = $EnemySide/EnemyInfo/HPLabel
@onready var battle_log: RichTextLabel = $BattleLog
@onready var turn_timer: Timer = $TurnTimer
@onready var current_speed_label: Label = $TopUI/CurrentSpeedLabel
@onready var turn_label: Label = $TopUI/TurnLabel
@onready var exit_button: Button = $ExitButton
@onready var speed_1x_button: Button = $TopUI/SpeedControlPanel/Speed1xButton
@onready var speed_2x_button: Button = $TopUI/SpeedControlPanel/Speed2xButton
@onready var speed_5x_button: Button = $TopUI/SpeedControlPanel/Speed5xButton
@onready var speed_10x_button: Button = $TopUI/SpeedControlPanel/Speed10xButton
@onready var speed_20x_button: Button = $TopUI/SpeedControlPanel/Speed20xButton

# 战斗数据
var player_data: Dictionary = {
	"name": "玩家",
	"max_hp": 100,
	"current_hp": 100,
	"attack": 20,
	"defense": 10,
	"attack_speed": 100
}

var enemy_data: Dictionary = {
	"name": "野生怪物",
	"max_hp": 80,
	"current_hp": 80,
	"attack": 15,
	"defense": 5,
	"attack_speed": 80
}

# 基于攻击速度的行动系统
var action_queue: Array = []  # 行动队列
var battle_active: bool = true
var base_turn_delay: float = 1.5  # 基础行动间隔时间
var current_speed_multiplier: float = 1.0  # 当前速度倍数
var turn_delay: float = 1.5  # 实际行动间隔时间
var current_action_index: int = 0
# 预先计算的掉落物品
var predetermined_drops: Array[Dictionary] = []

func _ready():
	# 初始化战斗界面
	setup_battle_ui()
	
	# 连接按钮信号
	exit_button.pressed.connect(_on_exit_button_pressed)
	speed_1x_button.pressed.connect(_on_speed_1x_pressed)
	speed_2x_button.pressed.connect(_on_speed_2x_pressed)
	speed_5x_button.pressed.connect(_on_speed_5x_pressed)
	speed_10x_button.pressed.connect(_on_speed_10x_pressed)
	speed_20x_button.pressed.connect(_on_speed_20x_pressed)
	
	# 从PlayerManager获取保存的速度设置
	if PlayerManager:
		current_speed_multiplier = PlayerManager.get_battle_speed_multiplier()
		update_speed_buttons()
		update_turn_delay()
		update_current_speed_display()
	
	# 开始战斗
	start_battle()

func setup_battle_ui():
	"""设置战斗界面"""
	# 设置玩家信息
	player_name_label.text = player_data.name
	player_hp_bar.max_value = player_data.max_hp
	player_hp_bar.value = player_data.current_hp
	player_hp_label.text = "HP: %d/%d" % [player_data.current_hp, player_data.max_hp]
	
	# 确保显示正确的当前生命值
	print("战斗界面设置 - 玩家生命值: %d/%d, 攻击速度: %d" % [player_data.current_hp, player_data.max_hp, player_data.attack_speed])
	
	# 设置敌人信息
	enemy_name_label.text = enemy_data.name
	enemy_hp_bar.max_value = enemy_data.max_hp
	enemy_hp_bar.value = enemy_data.current_hp
	enemy_hp_label.text = "HP: %d/%d" % [enemy_data.current_hp, enemy_data.max_hp]
	
	print("敌人信息 - 生命值: %d/%d, 攻击速度: %d" % [enemy_data.current_hp, enemy_data.max_hp, enemy_data.attack_speed])
	
	# 设置初始回合标签
	turn_label.text = "准备战斗..."
	
	# 清空战斗日志
	battle_log.clear()
	add_battle_log("战斗开始！")
	add_battle_log_with_colors("玩家攻击速度: %d, %s攻击速度: %d" % [player_data.attack_speed, enemy_data.name, enemy_data.attack_speed], 
		"", enemy_data.name, "", "enemy")

func start_battle():
	"""开始战斗"""
	battle_active = true
	
	# 计算行动队列
	calculate_action_queue()
	current_action_index = 0
	
	# 更新初始回合显示
	update_turn_display()
	
	# 设置行动计时器
	turn_timer.wait_time = turn_delay
	turn_timer.timeout.connect(_on_action_timeout)
	turn_timer.start()

func _on_action_timeout():
	"""行动超时处理"""
	if not battle_active or action_queue.is_empty():
		return
	
	# 执行当前行动
	var current_action = action_queue[current_action_index]
	if current_action == "player":
		player_attack()
	else:
		enemy_attack()
	
	# 检查战斗是否结束
	if check_battle_end():
		return
	
	# 移动到下一个行动
	current_action_index += 1
	if current_action_index >= action_queue.size():
		# 重新计算行动队列
		calculate_action_queue()
		current_action_index = 0
	
	# 更新回合显示
	update_turn_display()
	
	# 重新启动计时器
	turn_timer.start()

func player_attack():
	"""玩家攻击"""
	var damage = calculate_damage(player_data.attack, enemy_data.defense)
	enemy_data.current_hp = max(0, enemy_data.current_hp - damage)
	
	# 更新UI
	enemy_hp_bar.value = enemy_data.current_hp
	enemy_hp_label.text = "HP: %d/%d" % [enemy_data.current_hp, enemy_data.max_hp]
	
	# 添加战斗日志
	add_battle_log_with_colors("%s 攻击了 %s，造成 %d 点伤害！" % [player_data.name, enemy_data.name, damage], 
		player_data.name, enemy_data.name, "player", "enemy")
	
	# 播放攻击动画
	play_attack_animation(player_sprite)

func enemy_attack():
	"""敌人攻击"""
	var damage = calculate_damage(enemy_data.attack, player_data.defense)
	player_data.current_hp = max(0, player_data.current_hp - damage)
	
	# 更新UI
	player_hp_bar.value = player_data.current_hp
	player_hp_label.text = "HP: %d/%d" % [player_data.current_hp, player_data.max_hp]
	
	# 添加战斗日志
	add_battle_log_with_colors("%s 攻击了 %s，造成 %d 点伤害！" % [enemy_data.name, player_data.name, damage], 
		enemy_data.name, player_data.name, "enemy", "player")
	
	# 播放攻击动画
	play_attack_animation(enemy_sprite)

func calculate_damage(attack: int, defense: int) -> int:
	"""计算伤害"""
	var base_damage = attack - defense
	var random_factor = randf_range(0.8, 1.2)  # 80%-120%的随机伤害
	return max(1, int(base_damage * random_factor))  # 至少造成1点伤害

func play_attack_animation(sprite: TextureRect):
	"""播放攻击动画"""
	var tween = create_tween()
	var original_position = sprite.position
	
	# 前冲动画
	tween.tween_property(sprite, "position:x", original_position.x + 20, 0.2)
	tween.tween_property(sprite, "position:x", original_position.x, 0.2)

func calculate_action_queue():
	"""计算行动队列，基于攻击速度"""
	action_queue.clear()
	
	var player_speed = player_data.attack_speed
	var enemy_speed = enemy_data.attack_speed
	
	# 计算最大公约数来确定队列长度
	var max_speed = max(player_speed, enemy_speed)
	var queue_length = max_speed / 10  # 每10点速度一个基础单位
	
	# 计算每个角色在队列中的行动次数
	var player_actions = int(float(player_speed) / max_speed * queue_length)
	var enemy_actions = int(float(enemy_speed) / max_speed * queue_length)
	
	# 确保至少有一次行动
	player_actions = max(1, player_actions)
	enemy_actions = max(1, enemy_actions)
	
	# 创建行动队列
	var total_actions = player_actions + enemy_actions
	var player_interval = float(total_actions) / player_actions
	var enemy_interval = float(total_actions) / enemy_actions
	
	# 按时间顺序插入行动
	var actions_with_time = []
	for i in range(player_actions):
		actions_with_time.append({"type": "player", "time": i * player_interval})
	for i in range(enemy_actions):
		actions_with_time.append({"type": "enemy", "time": i * enemy_interval})
	
	# 按时间排序
	actions_with_time.sort_custom(func(a, b): return a.time < b.time)
	
	# 提取行动类型到队列
	for action in actions_with_time:
		action_queue.append(action.type)
	
	print("行动队列计算完成: ", action_queue)
	print("玩家速度: %d, 敌人速度: %d" % [player_speed, enemy_speed])

func update_turn_display():
	"""更新回合显示"""
	if action_queue.is_empty():
		return
	
	var current_actor = action_queue[current_action_index]
	if current_actor == "player":
		turn_label.text = "当前行动: %s" % player_data.name
	else:
		turn_label.text = "当前行动: %s" % enemy_data.name

func check_battle_end() -> bool:
	"""检查战斗是否结束"""
	if player_data.current_hp <= 0:
		end_battle(false)  # 玩家失败
		return true
	elif enemy_data.current_hp <= 0:
		end_battle(true)   # 玩家胜利
		return true
	
	return false

func end_battle(victory: bool):
	"""结束战斗"""
	print("[DEBUG] battle_scene end_battle 被调用，victory: ", victory)
	battle_active = false
	turn_timer.stop()
	
	if victory:
		add_battle_log_with_colors("胜利！%s 被击败了！" % enemy_data.name, 
			"", enemy_data.name, "", "enemy")
		
		# 简化奖励显示为四句话
		var reward_summary = get_battle_reward_summary(predetermined_drops)
		
		# 显示物品奖励
		if not reward_summary.items.is_empty():
			add_battle_log("获得物品: %s" % reward_summary.items)
		
		# 显示幻兽奖励
		if not reward_summary.phantom_beasts.is_empty():
			add_battle_log("获得幻兽: %s" % reward_summary.phantom_beasts)
		
		# 显示经验奖励
		if enemy_data.has("exp_reward"):
			var total_exp = enemy_data.exp_reward
			if total_exp > 0:
				add_battle_log("获得经验: 玩家和幻兽各获得%d点" % total_exp)
		
		# 显示金币奖励
		if reward_summary.gold > 0:
			add_battle_log("获得金币: %d" % reward_summary.gold)
		
		# 胜利时等待3秒让玩家看到结果
		await get_tree().create_timer(3.0).timeout
	else:
		add_battle_log_with_colors("失败！%s 被击败了..." % player_data.name, 
			"", player_data.name, "", "player")
		add_battle_log("\n[color=yellow]1秒后自动返回场景...[/color]")
		
		# 失败时只等待1秒就返回
		await get_tree().create_timer(1.0).timeout
	
	print("[DEBUG] battle_scene 发送 battle_ended 信号，victory: ", victory)
	var defeated_enemy: Dictionary = enemy_data if victory else {}
	battle_ended.emit(victory, player_data.current_hp, defeated_enemy)

func add_battle_log(text: String):
	"""添加战斗日志"""
	battle_log.append_text(text + "\n")
	# 自动滚动到底部
	battle_log.scroll_to_line(battle_log.get_line_count() - 1)

func add_battle_log_with_colors(text: String, attacker_name: String = "", target_name: String = "", attacker_team: String = "", target_team: String = ""):
	"""添加带颜色的战斗日志"""
	var colored_text = text
	
	# 为攻击者名称添加颜色
	if attacker_name != "":
		var attacker_color = "[color=green]" if attacker_team == "player" else "[color=plum]"
		colored_text = colored_text.replace(attacker_name, attacker_color + attacker_name + "[/color]")
	
	# 为目标名称添加颜色
	if target_name != "" and target_name != attacker_name:
		var target_color = "[color=green]" if target_team == "player" else "[color=plum]"
		colored_text = colored_text.replace(target_name, target_color + target_name + "[/color]")
	
	battle_log.append_text(colored_text + "\n")
	# 自动滚动到底部
	battle_log.scroll_to_line(battle_log.get_line_count() - 1)

func get_battle_reward_summary(drops: Array[Dictionary]) -> Dictionary:
	"""获取战斗奖励汇总"""
	var summary = {
		"items": "",
		"phantom_beasts": "",
		"gold": 0
	}
	
	var item_list: Array[String] = []
	var beast_list: Array[String] = []
	
	# 分类处理掉落物品
	for drop in drops:
		var item_name = get_item_name(drop["type"], drop["id"])
		var quantity = drop["quantity"]
		
		if drop["type"] == "gold":
			summary.gold += quantity
		elif drop["type"] == "phantom_beast":
			if quantity > 1:
				beast_list.append("%s x%d" % [item_name, quantity])
			else:
				beast_list.append(item_name)
		else:
			if quantity > 1:
				item_list.append("%s x%d" % [item_name, quantity])
			else:
				item_list.append(item_name)
	
	# 合并为字符串
	if not item_list.is_empty():
		summary.items = ", ".join(item_list)
	if not beast_list.is_empty():
		summary.phantom_beasts = ", ".join(beast_list)
	
	return summary

func get_item_name(item_type: String, item_id: String) -> String:
	"""获取物品名称"""
	match item_type:
		"gold":
			return "金币"
		"equipment":
			if ItemManager != null:
				var equipment_data = ItemManager.get_equipment_by_id(item_id)
				if equipment_data != null:
					return equipment_data.name
			return item_id
		"consumable":
			if ItemManager != null:
				var consumable_data = ItemManager.get_consumable_by_id(item_id)
				if consumable_data != null:
					return consumable_data.name
			return item_id
		"material":
			if ItemManager != null:
				var material_data = ItemManager.get_material_by_id(item_id)
				if material_data != null:
					return material_data.name
			return item_id
		"phantom_beast":
			# 幻兽幼崽掉落
			if PhantomBeastManager:
				var beast_config = PhantomBeastManager.get_phantom_beast_config(item_id)
				if beast_config != null:
					return beast_config.name + "幼崽"
			return item_id + "幼崽"
		_:
			return item_id

func display_drops_with_merged_gold(drops: Array[Dictionary]):
	"""显示掉落物品，将金币合并显示在最后"""
	var total_gold = 0
	var other_drops: Array[Dictionary] = []
	
	# 分离金币和其他物品
	for drop in drops:
		if drop["type"] == "gold":
			total_gold += drop["quantity"]
		else:
			other_drops.append(drop)
	
	# 先显示其他物品
	for drop in other_drops:
		var item_name = get_item_name(drop["type"], drop["id"])
		var quantity = drop["quantity"]
		
		if quantity > 1:
			add_battle_log("获得: %s x%d" % [item_name, quantity])
		else:
			add_battle_log("获得: %s" % item_name)
	
	# 最后显示合并的金币
	if total_gold > 0:
		add_battle_log("获得: 金币 x%d" % total_gold)

func set_player_data(data: Dictionary):
	"""设置玩家数据"""
	player_data = data.duplicate()
	if is_node_ready():
		setup_battle_ui()

func set_enemy_data(data: Dictionary):
	"""设置敌人数据"""
	enemy_data = data.duplicate()
	
	# 加载敌人图像
	if enemy_data.has("sprite_path") and enemy_sprite != null:
		var sprite_path = enemy_data.sprite_path
		print("尝试加载敌人图像: ", sprite_path)
		var texture = load(sprite_path)
		if texture != null:
			enemy_sprite.texture = texture
			print("成功加载敌人图像")
		else:
			print("错误：无法加载敌人图像 ", sprite_path)
	else:
		print("警告：没有敌人图像路径或enemy_sprite为空")
	
	if is_node_ready():
		setup_battle_ui()

func set_predetermined_drops(drops: Array[Dictionary]):
	"""设置预先计算的掉落物品"""
	predetermined_drops = drops.duplicate()

func _on_exit_button_pressed():
	"""逃跑按钮处理"""
	if not battle_active:
		return
	
	# 逃跑成功率（可以根据需要调整）
	var escape_chance = 0.8
	if randf() < escape_chance:
		add_battle_log("成功逃跑了！")
		end_battle(false)  # 逃跑算作失败，但不会有惩罚
	else:
		add_battle_log("逃跑失败！")
		# 逃跑失败，敌人获得一次攻击机会
		enemy_attack()
		if check_battle_end():
			return
		# 重新启动计时器
		turn_timer.start()

# 速度控制按钮处理
func _on_speed_1x_pressed():
	"""1倍速按钮处理"""
	set_battle_speed(1.0)

func _on_speed_2x_pressed():
	"""2倍速按钮处理"""
	set_battle_speed(2.0)

func _on_speed_5x_pressed():
	"""5倍速按钮处理"""
	set_battle_speed(5.0)

func _on_speed_10x_pressed():
	"""10倍速按钮处理"""
	set_battle_speed(10.0)

func _on_speed_20x_pressed():
	"""20倍速按钮处理"""
	set_battle_speed(20.0)

func set_battle_speed(multiplier: float):
	"""设置战斗速度"""
	current_speed_multiplier = multiplier
	update_turn_delay()
	update_speed_buttons()
	
	# 保存到PlayerManager
	if PlayerManager:
		PlayerManager.set_battle_speed_multiplier(multiplier)
	
	# 如果计时器正在运行，重新设置等待时间
	if turn_timer.time_left > 0:
		var remaining_ratio = turn_timer.time_left / turn_timer.wait_time
		turn_timer.wait_time = turn_delay
		turn_timer.start(turn_delay * remaining_ratio)
	
	add_battle_log("战斗速度设置为: %sx" % multiplier)
	update_current_speed_display()

func update_turn_delay():
	"""更新行动间隔时间"""
	turn_delay = base_turn_delay / current_speed_multiplier
	turn_timer.wait_time = turn_delay

func update_speed_buttons():
	"""更新速度按钮状态"""
	speed_1x_button.button_pressed = (current_speed_multiplier == 1.0)
	speed_2x_button.button_pressed = (current_speed_multiplier == 2.0)
	speed_5x_button.button_pressed = (current_speed_multiplier == 5.0)
	speed_10x_button.button_pressed = (current_speed_multiplier == 10.0)
	speed_20x_button.button_pressed = (current_speed_multiplier == 20.0)

func update_current_speed_display():
	"""更新当前速度显示"""
	if current_speed_label:
		current_speed_label.text = "当前战斗速度: %sx" % current_speed_multiplier
